package com.kaige.asktaoplugin60.utils;

import com.kaige.asktaoplugin60.config.GameConfig;
import com.kaige.asktaoplugin60.config.TcpInitChannel;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * 客户端工具类
 */
@Slf4j
public class ClientUtil {

    /**
     * 方法一：基于netty，实现客户端连接游戏服务端
     *
     * @param ip             服务端IP地址
     * @param port           端口号
     * @param channelHandler Channel处理器
     * @return 包含Channel和NioEventLoopGroup的数组，如果连接失败则Channel为null
     */
    public static Object[] connectToGameService(String ip, int port, ChannelHandler channelHandler) {
        NioEventLoopGroup nio = new NioEventLoopGroup();
        Channel c = null;
        try {
            c = new Bootstrap()
                    .group(nio)
                    .option(ChannelOption.SO_REUSEADDR, true)
                    .channel(NioSocketChannel.class)
                    .handler(new TcpInitChannel(channelHandler))
                    // 链接到游戏服务端的IP和端口
                    .connect(new InetSocketAddress(ip, port))
                    .sync()
                    .channel();
        } catch (Exception e) {
            log.error("连接到游戏服务端失败，地址: {}:{}", ip, port, e);
            // 如果连接失败，关闭NioEventLoopGroup
            nio.shutdownGracefully();
        }
        return new Object[]{c, nio};
    }

}